package com.googlecode.totallylazy.reducers;

import com.googlecode.totallylazy.Function;
import com.googlecode.totallylazy.Functions;
import com.googlecode.totallylazy.ReducerCombinerFunction;

import java.util.Collection;
import java.util.concurrent.Callable;

public abstract class CollectionReducer<T, R, C extends Collection<R>> extends ReducerCombinerFunction<T, C> {
    protected final Function<C> identity;

    public CollectionReducer(Callable<? extends C> identity) {this.identity = Functions.function(identity);}

    @Override
    public C combine(C a, C b) throws Exception {
        C collection = identity();
        collection.addAll(a);
        collection.addAll(b);
        return collection;
    }

    @Override
    public C identity() {
        return identity.apply();
    }
}
